package face.pay.web.file.service.impl;

import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.sdk.OSSUtils;
import face.pay.dao.FileInfoDao;
import face.pay.dao.OemConfigInfoDao;
import face.pay.dao.OemInfoDao;
import face.pay.entity.FileInfo;
import face.pay.entity.OemConfigInfo;
import face.pay.entity.UserInfo;
import face.pay.server.IServerAddressServer;
import face.pay.util.ResultMessage;
import face.pay.web.file.service.IfileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service
@Slf4j
public class FileServiceImpl implements IfileService {

    @Autowired
    private OemConfigInfoDao oemConfigInfoDao;

    @Autowired
    private OemInfoDao oemInfoDao;

    @Autowired
    private FileInfoDao fileInfoDao;

    @Autowired
    private IServerAddressServer iServerAddress;


    @Override
    @Transactional
    public ResultMessage upload(MultipartFile file, UserInfo loginUser) throws Exception {

        Integer oemId = loginUser.getOemId();

        OemConfigInfo configInfo =  this.oemConfigInfoDao.getByOemId(oemId);

        String fileName = file.getOriginalFilename();

        FileInfo fileInfo = new FileInfo(oemId,loginUser.getId(),fileName,"");
        String  fullName = fileInfo.createFullName(oemId);
        fileInfo.setFileName(fileName);
        fileInfo.setCreatedBy(loginUser.getId());

        this.fileInfoDao.insert(fileInfo);

        PutObjectResult putObjectResult =  OSSUtils.putOSS(configInfo.getEndPoint(),configInfo.getAccessKeyId(),configInfo.getAccessKeySecret(),configInfo.getBucket(),fullName,file.getBytes(),false);

        if(putObjectResult!=null){

            return ResultMessage.createSuccess(fileInfo);

        }
        return ResultMessage.createFail();
    }
}
